﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace RESP_IIWaterAssessment
{
    public partial class MembersForm : Form
    {
        public MembersForm()
        {
            InitializeComponent();
        }
        int regID, avpID;
        int? meetingId;
        bool ShowData = false;
        //IQueryable<tb_member> res;
        IQueryable<RESP_IIWaterAssessment.Entity.tb_member> res;
        RESP_IIWaterAssessment.Entity.tb_member member;
        RESP_IIWaterAssessment.Entity.RESP_addDataContext resp_data = new RESP_IIWaterAssessment.Entity.RESP_addDataContext(DBClass.RESPContext.Connection);
        //tb_member member;
        int rowIndex = -1;
        static int  lenarray=60;
        Array edlist = Array.CreateInstance(typeof(String), lenarray);
        string[] edlst = new string[4];

        private void MembersForm_Load(object sender, EventArgs e)
        {
            cbRegion.SelectedIndexChanged -= cbRegion_SelectedIndexChanged;
            cbRegion.DataSource = UtilClass.FillCBRegions();
            cbRegion.DisplayMember = "Name";
            cbRegion.ValueMember = "ID";

            if (InformationClass.isAdmin)
            {
                cbRegion.SelectedIndex = -1;
                cbRegion.Text = string.Empty;
                cbRegion.SelectedIndexChanged += new EventHandler(cbRegion_SelectedIndexChanged);
            }
            else
            {
                cbRegion.Enabled = false;
                regID = InformationClass.regionID;
                cbRegion.SelectedIndexChanged += new EventHandler(cbRegion_SelectedIndexChanged);
                cbRegion.SelectedValue = regID;
                cbRegion_SelectedIndexChanged(cbRegion, null);
                cbAVP.Enabled = true;
                cbAVP.Text = string.Empty;

            }
            //res = resp_data.tb_members.Where(wh => wh.ID > 0);
            //res = resp_data.tb_members.Where(wh => wh.ID > 0);
            //DBClass.Members
            edlst[0] = UtilClass.GetCategoryDisplayName(0, "Education");
            edlst[1] = UtilClass.GetCategoryDisplayName(1, "Education");
            edlst[2] = UtilClass.GetCategoryDisplayName(2, "Education");
            edlst[3] = UtilClass.GetCategoryDisplayName(3, "Education");
            //edlist.SetValue(UtilClass.GetCategoryDisplayName(0, "Education"), 0);
            //edlist.SetValue(UtilClass.GetCategoryDisplayName(1, "Education"), 1);
            //edlist.SetValue(UtilClass.GetCategoryDisplayName(2, "Education"), 2);
            //edlist.SetValue(UtilClass.GetCategoryDisplayName(3, "Education"), 3);
        }

        private void cbRegion_SelectedIndexChanged(object sender, EventArgs e)
        {
            //cbAVP.Items.Clear();
            //cbAVP.Text = string.Empty;
            //cbAVP.SelectedIndex = -1;
            cbAVP.SelectedIndexChanged -= cbAVP_SelectedIndexChanged;
            regID = Convert.ToInt32(cbRegion.SelectedValue);
            cbAVP.Enabled = true;
            cbAVP.DataSource = UtilClass.FillAVP(regID);
            cbAVP.DisplayMember = "Name";
            cbAVP.ValueMember = "ID";
            cbAVP.SelectedIndex = -1;
            cbAVP.Text = string.Empty;
            avpID = 0;
            cbAVP.SelectedIndexChanged += new EventHandler(cbAVP_SelectedIndexChanged);
        }

        private void buttonShow_Click(object sender, EventArgs e)
        {
            ShowMembers(res, string.Empty, string.Empty);
            for (int i = 0; i < dgvMembersInfo.RowCount; i++)
            {
                dgvMembersInfo.Rows[i].HeaderCell.Value = (i + 1).ToString();
            }
        }
        private void CreateReport()
        {
            int? avpID, cID, pID;
            DateTime? dt, dte;

        }
        private void ShowMembers(IQueryable<RESP_IIWaterAssessment.Entity.tb_member> res, string name, string position)
        {
            //if (cbAVP.SelectedIndex >= 0)
            //    res = res.Where(wh => wh.AVPID == avpID);
            //else
            //{
            //    res = res.Where(wh => UtilClass.GetAll_AVPID_in_regions(regID).Contains(wh.AVPID));
            //}
            //if (rbCommission.Checked)
            //    res = res.Where(wh => wh.TypeMeeting == 2);
            //if (rbConflCommission.Checked)
            //    res = res.Where(wh => wh.TypeMeeting == 3);
            //if (rbCouncil.Checked)
            //    res = res.Where(wh => wh.TypeMeeting == 4);
            //if (rbAll.Checked)
            //    res = res.Where(wh => wh.TypeMeeting == 2 || wh.TypeMeeting == 3 || wh.TypeMeeting == 4);

            //if (!string.IsNullOrEmpty(name))
            //    res = res.Where(wh => wh.Name.Contains(name));

            //if (!string.IsNullOrEmpty(position))
            //    res = res.Where(wh => wh.Position.Contains(position));
            dgvMembersInfo.DataSource = resp_data.MembersQuery(InformationClass.Lang, avpID,meetingId)
            //    .Select(se => new
            //{
            //    Name = se.Name,
            //    Position = se.Position,
            //    //Education = UtilClass.GetCategoryDisplayName((int)se.Education, "Education"),
            //    //Education = se.EdName,
            //    BirthDay = se.BirthDate,
            //    JobPlace = se.JobPlace,
            //    ContactInfo = se.ContactInfo
            //})
        ;
            if (InformationClass.Lang)
            {
                dgvMembersInfo.Columns["Name"].HeaderText = "Ф.И.О.";
                dgvMembersInfo.Columns["Position"].HeaderText = "Должность";
                dgvMembersInfo.Columns["EdName"].HeaderText = "Образование";
                dgvMembersInfo.Columns["BirthDate"].HeaderText = "Дата рождения";
                dgvMembersInfo.Columns["JobPlace"].HeaderText = "Место работы";
                dgvMembersInfo.Columns["ContactInfo"].HeaderText = "Контактная информация";
                dgvMembersInfo.Columns["TypeMeeting"].Visible = false;
                dgvMembersInfo.Columns["NameRus"].Visible = false;
            }
            else
            {
                dgvMembersInfo.Columns["Name"].HeaderText = "Ф.И.О.";
                dgvMembersInfo.Columns["Position"].HeaderText = "Лавозими";
                dgvMembersInfo.Columns["Education"].HeaderText = "Маълумоти";
                dgvMembersInfo.Columns["BirthDay"].HeaderText = "Туғилган санаси";
                dgvMembersInfo.Columns["JobPlace"].HeaderText = "Иш жойи";
                dgvMembersInfo.Columns["ContactInfo"].HeaderText = "Контакт маълумотлари";
                dgvMembersInfo.Columns["TypeMeeting"].Visible = false;
                dgvMembersInfo.Columns["NameRus"].Visible = false;
            }
            dgvMembersInfo.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvMembersInfo.AutoResizeColumns();
            if (dgvMembersInfo.RowCount <= 0)
            {
                if (InformationClass.Lang)
                    MessageBox.Show("Ничего не найденно.");
                else
                    MessageBox.Show("Ҳеч нарса топилмади.");
                rowIndex = -1;
            }
            else
                rowIndex = 0;

        }

        private void cbAVP_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbAVP.SelectedIndex >= 0)
                avpID = Convert.ToInt32(cbAVP.SelectedValue);
        }

        private void buttonSearch_Click(object sender, EventArgs e)
        {
            ShowMembers(res, tbEmpName.Text, tbPosition.Text);
        }

        private void tsButtonAdd_Click(object sender, EventArgs e)
        {
            if (avpID > 0)
            {
                EmployeesAVPForm empForm = new EmployeesAVPForm(avpID, true, null);
                if ((empForm.ShowDialog() == DialogResult.OK))
                {
                    member = empForm.member;
                    member.AVPID = avpID;
                    resp_data.tb_members.InsertOnSubmit(member);
                    try
                    {
                        resp_data.SubmitChanges();
                        MessageBox.Show(msgClass.msgSubmitChanges, msgClass.msgAchtung);
                        ShowMembers(res, string.Empty, string.Empty);
                    }
                    catch
                    {
                        MessageBox.Show(msgClass.msgError, msgClass.msgAchtung);
                        resp_data.tb_members.DeleteOnSubmit(member);
                        resp_data.SubmitChanges();
                    }

                }
            }
            else
                MessageBox.Show("Не выбранно АВП");
        }

        private void dgvMembersInfo_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
        {
            //rowIndex = e.Row.Index;
        }

        private void tstButtonEdit_Click(object sender, EventArgs e)
        {
            if (dgvMembersInfo.CurrentRow == null)
                return;

            rowIndex = dgvMembersInfo.CurrentRow.Index;
            if (rowIndex >= 0 && avpID > 0)
            {
                member = resp_data.tb_members
                    .Where(wh => wh.AVPID == avpID &&
                        wh.Name == dgvMembersInfo["Name", rowIndex].Value.ToString() &&
                        wh.Position == dgvMembersInfo["Position", rowIndex].Value.ToString() &&
                        wh.BirthDate == Convert.ToDateTime(dgvMembersInfo["BirthDate", rowIndex].Value))
                    .FirstOrDefault();
                EmployeesAVPForm empForm = new EmployeesAVPForm(avpID, false, member);

                if (empForm.ShowDialog() == DialogResult.OK)
                {
                    member.BirthDate = empForm.member.BirthDate;
                    member.ContactInfo = empForm.member.ContactInfo;
                    member.Education = empForm.member.Education;
                    member.JobPlace = empForm.member.JobPlace;
                    member.MemberType = empForm.member.MemberType;
                    member.Name = empForm.member.Name;
                    member.Position = empForm.member.Position;
                    member.TypeMeeting = empForm.member.TypeMeeting;
                    try
                    {
                        resp_data.SubmitChanges();
                        MessageBox.Show(msgClass.msgSubmitChanges, msgClass.msgAchtung);
                        ShowMembers(res, string.Empty, string.Empty);
                    }
                    catch
                    {
                        MessageBox.Show(msgClass.msgError, msgClass.msgAchtung);
                    }
                }
            }
        }

        private void tsButtonDelete_Click(object sender, EventArgs e)
        {
            if (dgvMembersInfo.CurrentRow == null)
                return;
            rowIndex = dgvMembersInfo.CurrentRow.Index;
            if (rowIndex >= 0 && avpID > 0)
            {
                string msg = InformationClass.Lang ? "Вы действительно хотите удалить " : "Ҳақиқатдан ҳам олиб ташламоқчимисиз";
                string titul = InformationClass.Lang ? "Удаление." : "Олиб ташлаш";
                if (MessageBox.Show(msg + dgvMembersInfo["Name", rowIndex].Value.ToString() + "?",titul , MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    member = resp_data.tb_members
                        .Where(wh => wh.AVPID == avpID &&
                            wh.Name == dgvMembersInfo["Name", rowIndex].Value.ToString() &&
                            wh.Position == dgvMembersInfo["Position", rowIndex].Value.ToString() &&
                            wh.BirthDate == Convert.ToDateTime(dgvMembersInfo["BirthDay", rowIndex].Value))
                        .FirstOrDefault();
                    resp_data.tb_members.DeleteOnSubmit(member);
                    resp_data.SubmitChanges();
                    ShowMembers(res, string.Empty, string.Empty);
                }
            }
            else
            {
                MessageBox.Show("Не выбранно АВП");
            }

        }

        private void rbAll_CheckedChanged(object sender, EventArgs e)
        {
            if (rbAll.Checked)
                meetingId = null;
        }


    }
}
